import 'dart:async';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

import '../networking/http_manager.dart';


Header? header() {
  return const ClassicHeader(
    // clamping: true,
    // position: IndicatorPosition.custom,
    // mainAxisAlignment: MainAxisAlignment.end,
    // position: IndicatorPosition.locator,
    // triggerOffset: 0,
    safeArea: false,
    // triggerOffset: 70,
    dragText: '下拉刷新',
    armedText: '松开立即刷新',
    readyText: '正在刷新...',
    processingText: "正在刷新...",
    processedText: "刷新完成",
    noMoreText: "没有数据",
    failedText: '刷新失败',
    messageText: "最后更新于：%T",
  );
}

// header: ClassicHeader(
//   clamping: true,
//   position: IndicatorPosition.locator,
//   mainAxisAlignment: MainAxisAlignment.end,
//   dragText: 'Pull to refresh'.tr,
//   armedText: 'Release ready'.tr,
//   readyText: 'Refreshing...'.tr,
//   processingText: 'Refreshing...'.tr,
//   processedText: 'Succeeded'.tr,
//   noMoreText: 'No more'.tr,
//   failedText: 'Failed'.tr,
//   messageText: 'Last updated at %T'.tr,
// ),
// footer: ClassicFooter(
//   position: IndicatorPosition.locator,
//   dragText: 'Pull to load'.tr,
//   armedText: 'Release ready'.tr,
//   readyText: 'Loading...'.tr,
//   processingText: 'Loading...'.tr,
//   processedText: 'Succeeded'.tr,
//   noMoreText: 'No more'.tr,
//   failedText: 'Failed'.tr,
//   messageText: 'Last updated at %T'.tr,
// ),

Footer? footer() {
  return const ClassicFooter(
    // position: IndicatorPosition.locator,
    dragText: '上拉加载更多',
    armedText: '松开立即加载',
    readyText: '正在加载更多...',
    processingText: "正在加载更多...",
    processedText: "加载完成",
    noMoreText: "没有更多数据",
    failedText: '加载失败',
    messageText: "最后更新于：%T",
  );
}

/// 根据不同状态来展示不同的视图
class LayoutRefreshView extends StatefulWidget {
  final Header? header;
  final Footer? footer;
  final EasyRefreshController? controller;
  String state = ResultCode.loading; //页面状态 默认为加载状态
  final FutureOr Function()? emptyRetry; // 空数据事件处理
  final FutureOr Function()? onRefresh;
  final FutureOr Function()? onLoad;
  Widget? child; //成功视图
  Widget? skeleton; // 骨架视图（页面加载中显示）

  LayoutRefreshView({super.key, required this.state, this.child, this.skeleton, this.emptyRetry, this.controller, this.header, this.footer, this.onRefresh, this.onLoad});
  @override
  _LayoutRefreshViewState createState() => _LayoutRefreshViewState();
}

class _LayoutRefreshViewState extends State<LayoutRefreshView> {
  late EasyRefresh _refresh;

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: EasyRefresh(
        header: widget.header??header(),
        footer: widget.footer??footer(),
        controller: widget.controller,
        onRefresh: widget.onRefresh,
        onLoad: widget.onLoad!=null ? () {
          if (widget.onLoad != null) {
            Future.delayed(const Duration(milliseconds: 500)).then((value){
              widget.onLoad!();
            });
          }
        } : null,
        child: getSubViews,
      ),
    );
  }


  Widget? get getSubViews {
    if (widget.state == ResultCode.loading) {
      return widget.skeleton ?? _loadingView;
    }else if (widget.state == ResultCode.error) {
      return _emptyView("网络失败，请刷新重试！", "no_internet.png");
    }else if (widget.state == ResultCode.empty_data) {
      return _emptyView("暂无内容，请刷新重试！", "empty_data.png");
    } else {
      // widget.state == ResultCode.success
      // widget.state == ResultCode.no_more_data
      return widget.child;
    }
  }

  Widget? get _loadingView {
    return ListView(
      children: [
        SizedBox(
          height: MediaQuery.of(context).size.height-270,
          child: const SpinKitCircle(color: Colors.blueAccent),
        ),
      ],
    );
  }

  Widget _emptyView(var text, var img) {
    return ListView(
      children: [
        SizedBox(
          height: MediaQuery.of(context).size.height-270,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset('assets/$img'),
              const SizedBox(height: 15),
              Text(text, style: const TextStyle(color: Colors.black45, fontSize: 16),),
            ],
          ),
        ),
      ],
    );
  }
}

